package burp;


import java.io.*;
import java.util.List;

/**
 * Created by shuaidong on 2017/6/24.
 */
public class SqlmapStart implements  Runnable {
    private PrintWriter stdout;

    public SqlmapStart(PrintWriter stdout) {
        this.stdout = stdout;
    }

    public static final  String macOsShell = "#!/bin/sh\n" +
            "   osascript -e '\n" +
            "     tell application \"Terminal\"\n" +
            "       activate\n" +
            "       tell window 1\n" +
            "          do script \"sqlmap ; exit\"\n" +
            "       end tell\n" +
            "       set w_ids to (id of every window)\n" +
            "       repeat while w_ids contains win_id\n" +
            "         delay 1\n" +
            "         set w_ids to (id of every window)\n" +
            "       end repeat\n" +
            "    end tell'";

    public void run() {
        //是Mac运行的方法
        try {
            BufferedWriter bufferedWriter = null;
            if (Os.checkOs() == Os.OsType.MAC){
                List<String> filenameTmp = Context.getTmpFilenameTmp(false,Context.size);
                for (String temp:filenameTmp){
                    String shell = macOsShell.replace("sqlmap ; exit","sqlmap -r  "+temp);
                    File file = new File(Context.tmpFileFolderReq+ "/" +System.currentTimeMillis() + ".sh");
                    if (!file.exists()){
                        file.createNewFile();
                    }

                    bufferedWriter = new BufferedWriter(new FileWriter(file));
                    bufferedWriter.write(shell);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    Runtime.getRuntime().exec("sh "+file.getPath());
                }
            }
            //是windows运行的方法
            if (Os.checkOs() == Os.OsType.WINDOWS){
                StringBuilder stringBuilder = new StringBuilder();
                List<String> filenameTmp = Context.getTmpFilenameTmp(false,Context.size);
                BufferedWriter bw = null;
                for (String file:filenameTmp){
                    File batFile = new File(Context.tmpFileFolderReq+"/"+System.currentTimeMillis()+".bat");

                    if (!batFile.exists()){
                        batFile.createNewFile();
                    }
                    bw = new BufferedWriter(new FileWriter(batFile));
                    bw.write("sqlmap.py -r  "+file);

                    bw.flush();
                    bw.close();
                    String batFilePath = batFile.getPath().toString();

                    stdout.print("batFilePath"+batFilePath);

                    Runtime.getRuntime().exec("cmd /c start "+batFilePath);
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }


}
